import json

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import datetime
import math


class NeimengguWlcbsczj1182Policy(BaseTaxPolicySpider):
    name = "neimenggu_wlcbsczj_1182_policy"

    province: str = "内蒙古自治区"  # 取表格
    city: str = "乌兰察布市"  # 取表格
    county: str = ""  # 取表格
    park: str = "None"  # 取表格
    source: str = "乌兰察布市财政局"  # 取表格 同一个来源合并
    url: str = "http://czj.wulanchabu.gov.cn/bmwj/index.html"  # 注明入口网址，以便后续排错

    headers = {
        "Content-Type": "application/json;charset=UTF-8",
    }

    def start_requests(self):
        yield scrapy.Request(self.url, callback=self.return_content)

    def return_content(self, response, **kwargs):
        data_url = '/rmt' + response.xpath('//script').re_first(r"""dataurl:\s*"(.*)",""")
        params = response.xpath('//script').re_first(r"""params:\s*"(.*)",""")
        totalcount = response.xpath('//script').re_first(r"""totalcount:\s*(\d+),""")
        data = {
            "params": params,
            "pagesize": 20,
            "currpage": 1,
        }
        body = json.dumps(data, separators=(',', ':'))
        yield response.follow(data_url, method='POST', body=body, callback=self.parse_list,
                              meta={"data": data, 'totalcount': totalcount}, headers=self.headers)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.json()['data']:
            item = Item()
            item['source_url'] = self.url.replace("index.", f'{str(elem["docno"])}.')
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = datetime.datetime.fromtimestamp(elem['inputTime'] / 1000)
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield scrapy.Request(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            data = response.meta.get('data')
            total_page = response.meta.get('totalcount')
            for page_num in range(2, math.ceil(int(total_page) / 20) + 1):
                data['currpage'] = page_num
                body = json.dumps(data, separators=(',', ':'))
                yield response.follow(response.url, method='POST', body=body, callback=self.parse_list,
                                      headers=self.headers, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl neimenggu_wlcbsczj_1182_policy".split())
